#!/usr/bin/env python3
import argparse
import dns.resolver
import os
import sys
import httpx
from urllib.parse import urlparse
import socket
import re
import time


class brute_domain():
	def __init__(self):
		if not os.path.isdir("logs"):
			os.makedirs("logs")
		if not os.path.isdir("output"):
			os.makedirs("output")
		self.get_parser()
		self.awvs = "output/" + self.dn.strip('.') + "-awvs.csv"
		date  = time.strftime('%Y-%m-%d', time.localtime())
		self.log = "logs/" + date + ".log"
		self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 11.0; WOW64) AppleWebKit/532.33 (KHTML, like Gecko) Chrome/92.0.3100.97 Safari/533.39 SE 3.X MetaSr 1.1"}

	def get_parser(self):
		"""
		Receive parameter
		"""
		parser = argparse.ArgumentParser()
		parser.description='please enter parameters ...'
		parser.add_argument("-f", "--file", help="domain list", dest="dlist", type=str, default="dict/domain.txt")
		parser.add_argument("-d", "--domain", help="domain name", dest="dn", type=str, required=True)
		args = parser.parse_args()
		
		self.subdnlist = args.dlist
		dn = args.dn
		if dn.startswith('.'):
			self.dn = dn
		else:
			self.dn = "." + dn
	
	def testDomain(self):
		testdn = "kldsfklsfklsdfklsdfklas"
		try:
			subdomain = testdn + self.dn
			res = socket.gethostbyname(subdomain)
			print("%s ===> %s" % (subdomain, res))
			print("%s 可能开启了泛域名解析." % self.dn)
			return True
		except:
			return False
			
	def get_sub_domain(self):
		if self.testDomain():
			self.pan_dn_resolution()
		else:
			self.dn_resolution()
	
	def pan_dn_resolution(self):
		rurl = ["http://www" + self.dn, "https://www" + self.dn, "http://www" + self.dn + "/", "https://www" + self.dn + "/"]
		print("对比URL: ", rurl)
		print()
		print("="*30)
		urls = []
		n = 0
		with open(self.subdnlist) as dl:
			lines = dl.readlines()
		nsum = len(lines)
		for line in lines:
			n += 1
			print("\r[%d/%d] " % (n, nsum), end='')
			subdomain = line.strip() + self.dn

			ip = False
			try:
				ip = socket.gethostbyname(subdomain)
				host,url,title,rcode = self.GetRequest(subdomain)
				if url in rurl:
					continue
			except:
				host = False
			if host:
				log = "%s ===> %s ===> [%d] %s (%s)" % (subdomain, ip, rcode, url, title)
				with open(self.log, 'a+') as flog:
					flog.write(log + "\n")
				print(log)
				if rcode == 200:
					if host not in urls:
						with open(self.awvs, 'a+') as awvs:
							save = "%s,%s\n" % (host, title)
							awvs.write(save)
						urls.append(host)
			elif ip:
				log = "%s ===> %s ===> 无法访问" % (subdomain, ip)
				with open(self.log, 'a+') as flog:
					flog.write(log + "\n")
				print(log)

		print()
	
	def dn_resolution(self):
		urls = []
		n = 0
		with open(self.subdnlist) as dl:
			lines = dl.readlines()
		nsum = len(lines)
		for line in lines:
			n += 1
			print("\r[%d/%d] " % (n, nsum), end='')
			subdomain = line.strip() + self.dn
			ip = False
			try:
				ip = socket.gethostbyname(subdomain)
				host,url,title,rcode = self.GetRequest(subdomain)
			except:
				host = False
			if host:
				log = "%s ===> %s ===> [%d] %s (%s)" % (subdomain, ip, rcode, url, title)
				with open(self.log, 'a+') as flog:
					flog.write(log + "\n")
				print(log)
				if rcode == 200:
					if host not in urls:
						with open(self.awvs, 'a+') as awvs:
							save = "%s,%s\n" % (host, title)
							awvs.write(save)
						urls.append(host)
			elif ip:
				log = "%s ===> %s ===> 无法访问" % (subdomain, ip)
				with open(self.log, 'a+') as flog:
					flog.write(log + "\n")
				print(log)

		print()
	
	def GetRequest(self, subdomain, first="http"):
		if first=="http":
			url1 = "http://" + subdomain
			url2 = "https://" + subdomain
		else:
			url1 = "https://" + subdomain
			url2 = "http://" + subdomain
		try:
			res = httpx.get(url1,headers=self.headers, verify=False)
		except:
			try:
				res = httpx.get(url2,headers=self.headers, verify=False)
			except:
				return False
		url = str(res.url)
		rcode = res.status_code
		host = urlparse(url).scheme + "://" + urlparse(url).netloc
		try:
			title = re.findall('<title>(.+)</title>', res.read().decode('utf8'))[0]
		except:
			title = ''
		return host,url,title,rcode



brute_domain().get_sub_domain()
